package handle

import (
	"bufio"
	"go2/log"
	"io"
	"net"
	http_proxy "proxy/http"
	socks5_proxy "proxy/socks5"
	"strconv"
)

var (
	g_http_proxy   *http_proxy.ProxyHttpServer
	g_socks5_proxy *socks5_proxy.Server
)

func Init() {
	g_http_proxy = http_proxy.NewProxyHttpServer()
	g_socks5_proxy, _ = socks5_proxy.New(&socks5_proxy.Config{})
}

func Serve(conn io.ReadWriteCloser, addr string) {
	reader := bufio.NewReader(conn)
	firstByte, err := reader.Peek(1)
	if err != nil {
		log.Error("Failed to peek first byte:", err)
		return
	}

	switch firstByte[0] {
	case 0x05:
		client_ip, client_port, _ := net.SplitHostPort(addr)
		log.Debugf("Socks5 Client: %s:%s", client_ip, client_port)

		client_port_int, _ := strconv.Atoi(client_port)
		if err := g_socks5_proxy.Serve(conn, reader, net.ParseIP(client_ip), client_port_int); err != nil {
			log.Error("Failed to serve SOCKS5:", err)
		}

	default:
		log.Debugf("HTTP Client: %s", addr)
		g_http_proxy.Serve(conn, reader)
	}
}
